package com.reliable.service.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reliable.api.dto.ReliableExportPushRecord.PushStatusStatisticsDTO;
import com.reliable.api.param.IdParam;
import com.reliable.api.param.ReliableExportPushRecord.ReliableExportPushRecordPageParam;
import com.reliable.api.param.ReliableExportPushRecord.ReliableExportPushRecordStatisticsParam;
import com.reliable.api.param.ReliableExportPushRecord.ReliableExportPushRecordErrorStatisticsParam;
import com.reliable.common.core.domain.AjaxResult;
import com.reliable.common.core.page.TableDataInfo;
import com.reliable.common.utils.StringUtils;
import com.reliable.service.domain.ReliableExportPushRecord;
import com.reliable.service.service.IReliableExportPushRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 导出推送记录Controller
 * 
 * @author ruoyi
 * @date 2025-10-30
 */
@RestController
@RequestMapping("/reliable/export/push/record")
@Api(value = "导出推送记录控制器", tags = {"导出推送记录管理"})
public class ReliableExportPushRecordController {

    @Autowired
    private IReliableExportPushRecordService reliableExportPushRecordService;
    

    /**
     * 获取一周内每天的推送数据统计
     * @return 每天推送数量的统计Map，key为日期"yyyy-MM-dd"，value为数量
     */
    @PostMapping("/weekly")
    @ApiOperation("获取一周内每天的推送数据统计")
    public AjaxResult getWeeklyPushData() {
        List<Map<String, Object>> weeklyData = reliableExportPushRecordService.getWeeklyPushData();
        Map<String, Integer> result = new LinkedHashMap<>();
        
        // 初始化一周的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        for (int i = 6; i >= 0; i--) {
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, -i);
            String dateStr = sdf.format(calendar.getTime());
            result.put(dateStr, 0);
        }
        
        // 填充实际数据
        for (Map<String, Object> data : weeklyData) {
            String dateStr = data.get("date").toString();
            Integer count = Integer.valueOf(data.get("count").toString());
            result.put(dateStr, count);
        }
        
        return AjaxResult.success(result);
    }
    
    /**
     * 获取推送状态统计信息（百分比）
     * @return 各推送状态的百分比统计
     */
    @PostMapping("/statistics/status")
    @ApiOperation("获取推送状态统计信息（百分比）")
    public AjaxResult getPushStatusStatistics(@RequestBody ReliableExportPushRecordStatisticsParam param) {
        List<PushStatusStatisticsDTO> list = reliableExportPushRecordService.getPushStatusStatistics(param.getBeginTime(), param.getEndTime());

        // 计算总数
        long totalCount = list.stream()
                .mapToLong(PushStatusStatisticsDTO::getCount)
                .sum();

        // 初始化各状态计数
        long processingCount = 0;  // 1=处理中
        long successCount = 0;     // 2=成功
        long failedCount = 0;      // 3=失败
        long partialSuccessCount = 0; // 4=部分成功

        // 分别统计各状态数量
        for (PushStatusStatisticsDTO item : list) {
            switch (item.getPushStatus()) {
                case 1:
                    processingCount = item.getCount();
                    break;
                case 2:
                    successCount = item.getCount();
                    break;
                case 3:
                    failedCount = item.getCount();
                    break;
                case 4:
                    partialSuccessCount = item.getCount();
                    break;
            }
        }

        // 计算百分比
        Map<String, Object> result = new HashMap<>();
        result.put("total", totalCount);
        
        Map<String, String> percentages = new HashMap<>();
        percentages.put("processing", totalCount == 0 ? "0.00" : String.format("%.2f", (processingCount * 100.0) / totalCount));
        percentages.put("success", totalCount == 0 ? "0.00" : String.format("%.2f", (successCount * 100.0) / totalCount));
        percentages.put("failed", totalCount == 0 ? "0.00" : String.format("%.2f", (failedCount * 100.0) / totalCount));
        percentages.put("partialSuccess", totalCount == 0 ? "0.00" : String.format("%.2f", (partialSuccessCount * 100.0) / totalCount));
        
        result.put("percentages", percentages);
        
        // 同时返回详细数量
        Map<String, Long> counts = new HashMap<>();
        counts.put("processing", processingCount);
        counts.put("success", successCount);
        counts.put("failed", failedCount);
        counts.put("partialSuccess", partialSuccessCount);
        
        result.put("counts", counts);
        result.put("details", list);

        return AjaxResult.success(result);
    }
    
    /**
     * 获取错误信息统计
     * @return 错误信息分组统计结果
     */
    @PostMapping("/statistics/error")
    @ApiOperation("获取错误信息统计")
    public AjaxResult getErrorMessageStatistics(@RequestBody ReliableExportPushRecordErrorStatisticsParam param) {
        List<Map<String, Object>> errorData = reliableExportPushRecordService.getErrorMessageStatistics(param.getBeginTime(), param.getEndTime());
        
        // 构建返回结果
        Map<String, Object> result = new LinkedHashMap<>();
        
        // 计算总数
        long totalCount = errorData.stream()
                .mapToLong(data -> Long.parseLong(data.get("count").toString()))
                .sum();
        
        result.put("total", totalCount);
        result.put("data", errorData);
        
        return AjaxResult.success(result);
    }




//
//    /**
//     * 查询导出推送记录列表
//     */
//    @ApiOperation("查询导出推送记录列表")
//    @PostMapping("/list")
//    public AjaxResult list(@RequestBody ReliableExportPushRecordPageParam param) {
//        LambdaQueryWrapper<ReliableExportPushRecord> wrapper = new LambdaQueryWrapper<>();
//
//        // 根据导出记录ID查询
//        if (param.getExportRecordId() != null) {
//            wrapper.eq(ReliableExportPushRecord::getExportRecordId, param.getExportRecordId());
//        }
//
//        // 根据推送渠道查询
//        if (StringUtils.isNotEmpty(param.getChannel())) {
//            wrapper.eq(ReliableExportPushRecord::getChannel, param.getChannel());
//        }
//
//        // 根据城市查询
//        if (StringUtils.isNotEmpty(param.getCity())) {
//            wrapper.eq(ReliableExportPushRecord::getCity, param.getCity());
//        }
//
//        // 根据部门查询
//        if (StringUtils.isNotEmpty(param.getDepartment())) {
//            wrapper.eq(ReliableExportPushRecord::getDepartment, param.getDepartment());
//        }
//
//        // 根据推送状态查询
//        if (param.getPushStatus() != null) {
//            wrapper.eq(ReliableExportPushRecord::getPushStatus, param.getPushStatus());
//        }
//
//        IPage<ReliableExportPushRecord> page = reliableExportPushRecordService.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
//        TableDataInfo data = new TableDataInfo(page.getRecords(), (int) page.getTotal());
//        return AjaxResult.success(data);
//    }
//
//    /**
//     * 获取导出推送记录详细信息
//     */
//    @ApiOperation("获取导出推送记录详细信息")
//    @PostMapping(value = "/info")
//    public AjaxResult getInfo(@RequestBody IdParam param) {
//        ReliableExportPushRecord record = reliableExportPushRecordService.getById(param.getBusinessId());
//        return AjaxResult.success(record);
//    }
//
//    /**
//     * 新增导出推送记录
//     */
//    @ApiOperation("新增导出推送记录")
//    @PostMapping("/add")
//    public AjaxResult add(@RequestBody ReliableExportPushRecord param) {
//        return toAjax(reliableExportPushRecordService.save(param));
//    }
//
//    /**
//     * 修改导出推送记录
//     */
//    @ApiOperation("修改导出推送记录")
//    @PostMapping("/edit")
//    public AjaxResult edit(@RequestBody ReliableExportPushRecord param) {
//        return toAjax(reliableExportPushRecordService.updateById(param));
//    }
//
//    /**
//     * 删除导出推送记录
//     */
//    @ApiOperation("删除导出推送记录")
//    @PostMapping("/delete")
//    public AjaxResult remove(@RequestBody IdParam param) {
//        return toAjax(reliableExportPushRecordService.removeById(param.getBusinessId()));
//    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(boolean rows) {
        return rows ? AjaxResult.success() : AjaxResult.error();
    }
}